#pragma once
#include <iostream>
#include <vector>
#include <fstream>
#include <unistd.h>
#include <string>
#include <mutex>
#include <cassert>
#include <jsoncpp/json/json.h>
#include "../comm/httplib.h"
#include "oj_model.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace std;
    using namespace ns_model;
    using namespace ns_util;
    using namespace ns_view;
    using namespace httplib;

    // 提供服务的主机
    class Machine
    {
    public:
        std::string ip; // 服务ip
        int port;       // 服务端口
        uint64_t load;  // 服务负载
        std::mutex *mtx;
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine() {}

        uint64_t Load() // 返回当前负载情况
        {
            uint64_t _load = 0;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }

        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load=0;
            if(mtx) mtx->unlock();
        }

        void IncLoad() // 负载增加
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }

        void DescLoad() // 负载减少
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
    };

    const std::string machine_path = "../conf/service_machine.conf";

    // 负载均衡模块
    class LoadBalance
    {
    private:
        vector<Machine> machines; // 提供服务的主机
        // 存储的时machines的ID
        vector<int> online;  // 在线的主机
        vector<int> offline; // 离线的主机
        std::mutex mtx;

    public:
        LoadBalance()
        {
            assert(LoadMachines());
            LOG(Info) << "加载" << machine_path << "成功" << "\n";
        }

        bool LoadMachines()
        {
            ifstream in(machine_path);
            if (!in.is_open())
            {
                LOG(Info) << "加载" << machine_path << "失败" << "\n";
                return false;
            }

            std::string line;
            while (getline(in, line))
            {
                vector<string> tokens;
                StringUtil::SplitString(&tokens, line, ":");
                if (tokens.size() != 2)
                {
                    LOG(Warning) << "切分" << line << "失败" << "\n";
                    return false;
                }
                Machine mac;
                mac.ip = tokens[0];
                mac.port = atoi(tokens[1].c_str());
                mac.load = 0;
                mac.mtx = new mutex();
                online.push_back(machines.size());
                machines.push_back(mac);
            }

            in.close();
            return true;
        }

        bool SmartChoice(int *id, Machine **m)
        {
            mtx.lock();
            // 轮询式选择
            int online_num = online.size();
            if (online_num == 0)
            {
                mtx.unlock();
                LOG(Fatal) << "所以主机都已经离线，请尽快处理" << "\n";
                return false;
            }
            *id = online[0];
            *m = &machines[online[0]];
            uint64_t min_load = machines[online[0]].Load();
            for (int i = 1; i < online_num; i++)
            {
                uint64_t curr_load = machines[online[i]].Load();
                if (min_load > curr_load)
                {
                    *id = online[i];
                    *m = &machines[online[i]];
                    min_load = curr_load;
                }
            }
            mtx.unlock();
            return true;
        }

        void onlineMachine()
        {
            mtx.lock();
            online.insert(online.end(),offline.begin(),offline.end());
            offline.erase(offline.begin(),offline.end());
            mtx.unlock();
            LOG(INFO) << "所有的主机有上线啦!" << "\n";
        }

        void offlineMachine(int which)
        {
            mtx.lock();
            auto iter = online.begin();
            for (; iter != online.end(); iter++)
            {
                if (*iter == which)
                {
                    machines[*iter].ResetLoad();
                    online.erase(iter);
                    offline.push_back(which);
                    break;
                }
            }
            mtx.unlock();
        }

        void showMachines()
        {
            mtx.lock();
            std::cout << "当前在线主机列表: ";
            for (auto &id : online)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            std::cout << "当前离线主机列表: ";
            for (auto &id : offline)
            {
                std::cout << id << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }

        ~LoadBalance()
        {
        }
    };

    // 核心业务逻辑模块
    class Control
    {
    private:
        Model _model;             // 提供后台服务
        View _view;               // 渲染网页
        LoadBalance _loadBalance; // 核心负载均衡器
    public:
        Control() {}
        ~Control() {}

        void Recovery()
        {
            _loadBalance.onlineMachine();
        }

        bool AllQuestions(std::string *html)
        {
            bool ret = true;
            vector<Question> questions;
            if (_model.GetAllQuestion(&questions))
            {
                sort(questions.begin(), questions.end(), [](const struct Question &q1, const struct Question &q2){
                    return atoi(q1.name.c_str()) < atoi(q2.name.c_str());
                });
                _view.ExpandAllHtml(questions, html); // 渲染
            }
            else
            {
                *html = "获取题目失败，形成题目列表失败";
                ret = false;
            }
            return ret;
        }

        bool OneQuestion(const std::string &name, std::string *html)
        {
            bool ret = true;
            Question question;
            if (_model.GetOneQuestion(name, &question))
            {
                _view.ExpandOneHtml(question, html); // 渲染
            }
            else
            {
                *html = "指定题目" + name + "不存在";
                ret = false;
            }
            return ret;
        }

        void Judge(const std::string &name, const std::string &in_json, std::string *out_json)
        {
            // 0.得到题目信息
            Question q;
            _model.GetOneQuestion(name, &q);
            // 1.对用户的代码进行反序列化
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            // 2.构建完整代码
            Json::Value out_value;
            out_value["code"] = in_value["code"].asString() +"\n" + q.tail;
            out_value["input"] = in_value["input"].asString();
            out_value["cpu_limit"] = q.cpu_limit;
            out_value["mem_limit"] = q.mem_limit;

            Json::FastWriter writer;
            std::string compile_string = writer.write(out_value);

            // 3.选择负载最低的主机进行处理
            while (true)
            {
                Machine *m = nullptr;
                int id = 0;
                if (!_loadBalance.SmartChoice(&id, &m))
                {
                    break;
                }
                LOG(INFO) << " 选择主机成功, 主机id: " << id << "详情: " << m->ip << " : " << m->port <<"当前主机负载为："<< m->Load()<<"\n";
                // 4.发起http请求，得到结果
                Client cli(m->ip, m->port);
                m->IncLoad();
                if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                {
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DescLoad();
                        LOG(Info) << "请求编译和运行服务成功..." << "\n";
                        break;
                    }
                    m->DescLoad();
                }
                else
                {
                    LOG(ERROR) << " 当前请求的主机id: " << id << "详情: " << m->ip << ":" << m->port << " 可能已经离线" << "\n";
                    _loadBalance.offlineMachine(id);
                    _loadBalance.showMachines();
                }
                }
            }
        };
    }
